/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * telaPesquisarUsuario.java
 *
 * Created on 25/11/2012, 20:34:12
 */
package gui;

import Fachada.Fachada;
import classes.Usuario;
import erro.ConexaoException;
import erro.ConsultaException;
import erro.DaoException;
import erro.GeralException;
import java.util.ArrayList;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author George
 */
public class telaPesquisarUsuario extends javax.swing.JFrame {

    private static Fachada f;
    String cpf;

    /** Creates new form telaPesquisarUsuario */
    public telaPesquisarUsuario() {
        initComponents();
        this.setLocationRelativeTo(null);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        ButtonAltUsu = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        TableUsuario = new javax.swing.JTable();
        ButtonListarUsu = new javax.swing.JButton();
        txtBoxPesqCPFUsu = new javax.swing.JFormattedTextField();
        jButtonCancelar = new javax.swing.JButton();
        jButtonPesqUsu = new javax.swing.JButton();
        jLabel2 = new javax.swing.JLabel();
        jSeparator1 = new javax.swing.JSeparator();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 12));
        jLabel1.setText("CPF:");

        ButtonAltUsu.setText("ALTERAR");
        ButtonAltUsu.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                ButtonAltUsuActionPerformed(evt);
            }
        });

        TableUsuario.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null, null},
                {null, null, null, null, null},
                {null, null, null, null, null},
                {null, null, null, null, null}
            },
            new String [] {
                "CPF", "Nome", "Fone", "Login", "Perfil"
            }
        ));
        TableUsuario.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                TableUsuarioMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(TableUsuario);

        ButtonListarUsu.setText("LISTAR");
        ButtonListarUsu.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                ButtonListarUsuActionPerformed(evt);
            }
        });

        try {
            txtBoxPesqCPFUsu.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("###.###.###-##")));
        } catch (java.text.ParseException ex) {
            ex.printStackTrace();
        }
        txtBoxPesqCPFUsu.setFocusLostBehavior(javax.swing.JFormattedTextField.COMMIT);

        jButtonCancelar.setText("CANCELAR");
        jButtonCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonCancelarActionPerformed(evt);
            }
        });

        jButtonPesqUsu.setText("PESQUISAR");
        jButtonPesqUsu.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonPesqUsuActionPerformed(evt);
            }
        });

        jLabel2.setFont(new java.awt.Font("Tahoma", 0, 36));
        jLabel2.setText("Pesquisar Usuário");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(170, Short.MAX_VALUE)
                .addComponent(jLabel2)
                .addGap(145, 145, 145))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(154, Short.MAX_VALUE)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 311, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(132, 132, 132))
            .addGroup(layout.createSequentialGroup()
                .addGap(33, 33, 33)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 149, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(ButtonAltUsu, javax.swing.GroupLayout.PREFERRED_SIZE, 93, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(ButtonListarUsu, javax.swing.GroupLayout.PREFERRED_SIZE, 88, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(jButtonCancelar, javax.swing.GroupLayout.PREFERRED_SIZE, 98, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(57, 57, 57))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 521, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(txtBoxPesqCPFUsu, javax.swing.GroupLayout.PREFERRED_SIZE, 136, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jButtonPesqUsu, javax.swing.GroupLayout.PREFERRED_SIZE, 105, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(43, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGap(20, 20, 20)
                .addComponent(jLabel2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(txtBoxPesqCPFUsu, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButtonPesqUsu, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(20, 20, 20)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 197, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(27, 27, 27)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(ButtonListarUsu, javax.swing.GroupLayout.DEFAULT_SIZE, 34, Short.MAX_VALUE)
                    .addComponent(jButtonCancelar, javax.swing.GroupLayout.DEFAULT_SIZE, 34, Short.MAX_VALUE)
                    .addComponent(ButtonAltUsu, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(19, 19, 19))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void TableUsuarioMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_TableUsuarioMouseClicked
        int x = TableUsuario.getSelectedRow();
        int y = TableUsuario.getSelectedColumn();

        //Se o clique for duplo
        if (evt.getClickCount() == 1) {
            if (evt.getButton() == evt.BUTTON1) {//E o botão for o esquerdo

                txtBoxPesqCPFUsu.setText((String) TableUsuario.getValueAt(x, 0));

            }
        }
    }//GEN-LAST:event_TableUsuarioMouseClicked

    private void ButtonAltUsuActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ButtonAltUsuActionPerformed
        telaAlterarUsuario alterausu = new telaAlterarUsuario();
        alterausu.setVisible(true);

        Usuario usu = new Usuario();
        f = Fachada.getInstancia();
        cpf = txtBoxPesqCPFUsu.getText().replace(".", "");
        cpf = cpf.replace("-", "");

        usu.setCpfUsuario(cpf);
        try {
            try {
                f.pesquisarUsu(usu);
            } catch (GeralException ex) {
                JOptionPane.showMessageDialog(null, ex.getMessage());
            } catch (DaoException ex) {
                JOptionPane.showMessageDialog(null, ex.getMessage());
            }
            if (usu.getNomeUsuario() == null) {
                alterausu.setVisible(false);
                alterausu.dispose();
            } else {
                alterausu.codpf = usu.getCodPerfil();
                alterausu.LabelCodUsu.setText(Integer.toString(usu.getCodUsuario()));
                alterausu.txtBoxNomeUsu.setText(usu.getNomeUsuario());
                alterausu.txtBoxCPFUsu.setText(usu.getCpfUsuario());
                alterausu.txtBoxFoneUsu.setText(usu.getFoneUsuario());
                alterausu.txtBoxLoginUsu.setText(usu.getLoginUsuario());
                alterausu.txtBoxSenhaUsu.setText(usu.getSenhaUsuario());
                alterausu.selecionado();
            }
        } catch (ConexaoException ex) {
            JOptionPane.showMessageDialog(null, ex.getMessage());
        } catch (ConsultaException ex) {
            JOptionPane.showMessageDialog(null, ex.getMessage());
        }
    }//GEN-LAST:event_ButtonAltUsuActionPerformed

    private void ButtonListarUsuActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ButtonListarUsuActionPerformed
        listarTabela();
        txtBoxPesqCPFUsu.setText("");
    }//GEN-LAST:event_ButtonListarUsuActionPerformed

    private void jButtonCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonCancelarActionPerformed
        telaPesquisarUsuario tlpesqusu = new telaPesquisarUsuario();
        int i = JOptionPane.showConfirmDialog(null, "Deseja realmente Cancelar?", "Cancelar", JOptionPane.YES_NO_OPTION);
        if (i == JOptionPane.YES_OPTION) {
            telaPesquisarUsuario.this.setVisible(false);
            tlpesqusu.dispose();
        } else {
            repaint();
        }
    }//GEN-LAST:event_jButtonCancelarActionPerformed

    private void jButtonPesqUsuActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonPesqUsuActionPerformed

            TableUsuario.getColumnModel().getColumn(0).setPreferredWidth(150);
            TableUsuario.getColumnModel().getColumn(1).setPreferredWidth(300);
            TableUsuario.getColumnModel().getColumn(2).setPreferredWidth(130);
            TableUsuario.getColumnModel().getColumn(3).setPreferredWidth(100);
            TableUsuario.getColumnModel().getColumn(4).setPreferredWidth(130);
            DefaultTableModel modelo = (DefaultTableModel) TableUsuario.getModel();
            modelo.setNumRows(0);
            f = Fachada.getInstancia();
            Usuario usu = new Usuario();
            cpf = txtBoxPesqCPFUsu.getText().replace(".", "");
            cpf = cpf.replace("-", "");
            cpf = cpf.replace(" ", "");
            ArrayList<Usuario> lista = new ArrayList<Usuario>();
            try {
                usu.setCpfUsuario(cpf + "%");
                lista = (ArrayList<Usuario>) f.pesquisarUsuario(usu);
            } catch (ConexaoException ex) {
                JOptionPane.showMessageDialog(null, ex.getMessage());
            } catch (ConsultaException ex) {
            JOptionPane.showMessageDialog(null, ex.getMessage());
            }
            for (int i = 0; i < lista.size(); i++) {
                modelo.addRow(new Object[]{lista.get(i).getCpfUsuario(), lista.get(i).getNomeUsuario(),
                            lista.get(i).getFoneUsuario(), lista.get(i).getLoginUsuario(), lista.get(i).getNomePerfil()});
            }
            TableUsuario.setModel(modelo);
    }//GEN-LAST:event_jButtonPesqUsuActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(telaPesquisarUsuario.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(telaPesquisarUsuario.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(telaPesquisarUsuario.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(telaPesquisarUsuario.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new telaPesquisarUsuario().setVisible(true);
            }
        });
    }

    public void listarTabela() {
        TableUsuario.getColumnModel().getColumn(0).setPreferredWidth(150);
        TableUsuario.getColumnModel().getColumn(1).setPreferredWidth(300);
        TableUsuario.getColumnModel().getColumn(2).setPreferredWidth(130);
        TableUsuario.getColumnModel().getColumn(3).setPreferredWidth(100);
        TableUsuario.getColumnModel().getColumn(4).setPreferredWidth(130);
        DefaultTableModel modelo = (DefaultTableModel) TableUsuario.getModel();
        modelo.setNumRows(0);
        f = Fachada.getInstancia();
        Usuario usu = new Usuario();
        ArrayList<Usuario> lista = new ArrayList<Usuario>();
        try {
            lista = (ArrayList<Usuario>) f.listar(usu);
        } catch (ConsultaException ex) {
            JOptionPane.showMessageDialog(null, ex.getMessage());
        } catch (ConexaoException ex) {
            JOptionPane.showMessageDialog(null, ex.getMessage());
        }
        for (int i = 0; i < lista.size(); i++) {
            modelo.addRow(new Object[]{lista.get(i).getCpfUsuario(), lista.get(i).getNomeUsuario(),
                        lista.get(i).getFoneUsuario(), lista.get(i).getLoginUsuario(), lista.get(i).getNomePerfil()});
        }
        TableUsuario.setModel(modelo);
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton ButtonAltUsu;
    private javax.swing.JButton ButtonListarUsu;
    private javax.swing.JTable TableUsuario;
    private javax.swing.JButton jButtonCancelar;
    private javax.swing.JButton jButtonPesqUsu;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JFormattedTextField txtBoxPesqCPFUsu;
    // End of variables declaration//GEN-END:variables
}
